/**
 * 选择人员插件
 * 需要用到的js：ztree，select2，icheck
 * 使用说明：在需要弹出选择人员窗口的标签加上 onclick="openCoursewareModal();"
 * 确认选择人员按钮事件需要在使用的页面上实现如下方法:
     function confirmSelectCourseware(){
        var checkedCoursewareIds = $("#checkedCoursewareIds").val();//选择的人员id字符串集合
        if(checkedLecturerIds != ""){
            //根据id集合查询用户信息
            $.post(getCoursewareListByIdsUrl,{"coursewareIds":checkedCoursewareIds},function(data){
                var coursewareList = data;
                ...
            })
        }
    }
 */
var getCoursewarePageUrl = "/lrm/controller/courseware/getCoursewarePage";
var getCoursewareListUrl = "/lrm/controller/courseware/getCoursewareList";
var getCoursewareListByIdsUrl = "/lrm/controller/courseware/getCoursewareListByIds";



$(function(){
    var div = '<div id="loadCoursewareDiv"></div>';
    $("#mainScroll").after(div);
    loadCoursewareModal();
})

//加载选择人员窗体组件
function loadCoursewareModal(){
    $("#loadCoursewareDiv").load(getCoursewarePageUrl, function(){
        $("input[name='coursewareCheckboxAll']").iCheck({
            checkboxClass: "icheckbox_minimal-blue",
            radioClass: "iradio_minimal-blue",
            increaseArea: "20%"
        });
        $("input[name='coursewareCheckboxAll']").on("ifClicked", function(event){
            if(!$(this).prop("checked")){
                $("input[name='coursewareCheckboxSub']").iCheck("check");
                var checkedCoursewares = $("input[name='coursewareCheckboxSub']:checked");
                var checkedCoursewareArray = $("#checkedCoursewareIds").val().split(",");
                var checkedCoursewareStr = '';
                $.each(checkedCoursewares ,function(i,checkedCourseware){
                    var coursewareId = $(checkedCourseware).val();
                    if($.inArray(coursewareId, checkedCoursewareArray) < 0){
                        checkedCoursewareArray.push(coursewareId);
                        var coursewareName = $(checkedCourseware).attr("coursewareName");
                        checkedCoursewareStr+='<span class="btn btn-default btn-xs" id="checkedCourseware_'+coursewareId+'" style="margin: 0px 5px 5px 0px;">'+coursewareName+'<span aria-hidden="true" onclick=removeCheckedCourseware("'+coursewareId+'")>&nbsp;&times;</span></span>';
                    }
                });
                $("#checkedCoursewareIds").val(array_remove("", checkedCoursewareArray));
                $("#checkedCoursewareArea").append(checkedCoursewareStr);
            }else{
                $("input[name='coursewareCheckboxSub']").iCheck("uncheck");
                var uncheckedCoursewares = $("input[name='coursewareCheckboxSub']").not("input:checked");
                $.each(uncheckedCoursewares,function(i, uncheckedCourseware){
                    var coursewareId = $(uncheckedCourseware).val();
                    removeCheckedCourseware(coursewareId);
                });
            }
        });
    });
}

//打开选择讲师窗口
function openCoursewareModal(){
    searchCoursewareList(1);
    $("#courseware_modal").modal("show");
}
//关闭选择讲师窗口
function closeCoursewareModal(){
    $("#courseware_modal").modal("hide");
}

//加载讲师列表
function searchCoursewareList(pageNo){
    $("input[name='coursewareCheckboxAll']").iCheck("uncheck");
    var coursewareCodeOrName = $("#coursewareCodeOrName").val();
    var params = {"coursewareCodeOrName":coursewareCodeOrName, "pageNo":pageNo};
    $.post(getCoursewareListUrl, params, function(data){
        var coursewareListStr = "";
        var openPage = data.openPage;
        if(openPage.rows.length > 0){
            var pageNo = openPage.pageNo;
            var pageSize = openPage.pageSize;
            var total = openPage.total;
            var totalPages = openPage.totalPages;
            var checkNum = 0;
            $.each(openPage.rows,function(i,courseware){
                var indexNo = (pageNo-1)*pageSize+(i+1);
                var coursewareId = courseware.coursewareId;
                var coursewareCode = courseware.coursewareCode;
                var coursewareName = courseware.coursewareName;
                var fileType = courseware.fileType;
                var duration = courseware.duration;
                var deviceType = courseware.deviceType;
                var isOpened = courseware.isOpened;
                var isOpenedStr = "";
                if(isOpened == "1") {
                    isOpenedStr = "是";
                } else {
                    isOpenedStr = "否";
                }
                var deviceTypeStr = "";
                if(deviceType == "PC") {
                    deviceTypeStr = "PC";
                } else if(deviceType == "MOBILE") {
                    deviceTypeStr = "移动";
                } else if(deviceType == "PC,MOBILE") {
                    deviceTypeStr = "PC/移动";
                } else if(deviceType == "MOBILE,PC") {
                    deviceTypeStr = "PC/移动";
                }
                coursewareListStr += '<tr><td><input class="coursewareCheckboxSub" type="checkbox" name="coursewareCheckboxSub" ';
                var checkedCoursewareArray = $("#checkedCoursewareIds").val().split(",");
                if($.inArray(coursewareId, checkedCoursewareArray)>=0){
                    ++checkNum;
                    coursewareListStr += 'checked="checked" ';
                }
                coursewareListStr += 'value="'+ coursewareId +'" coursewareName="'+coursewareName+'"></td><td>'+indexNo+'</td>';
                coursewareListStr += '<td>'+coursewareCode+'</td>';
                coursewareListStr += '<td>'+coursewareName+'</td>';
                coursewareListStr += '<td>'+fileType+'</td>';
                coursewareListStr += '<td>'+duration+'</td>';
                coursewareListStr += '<td>'+deviceTypeStr+'</td>';
                coursewareListStr += '<td>'+isOpenedStr+'</td>';
                coursewareListStr += '</tr>';
            });
            $("#coursewareList").html(coursewareListStr);
            var checkBoxNum = $("input[name='coursewareCheckboxSub']").length;
            if(checkNum == checkBoxNum){
                $("input[name='coursewareCheckboxAll']").iCheck("check");
            }
            if(total > pageSize){
                coursewarePageLimit(pageNo,totalPages,"coursewarePageLimit");
            } else {
                $("#coursewarePageLimit").html("");
            }
            $("input[name='coursewareCheckboxSub']").iCheck({
                checkboxClass: "icheckbox_minimal-blue",
                radioClass: "iradio_minimal-blue",
                increaseArea: "20%"
            });
            $("input[name='coursewareCheckboxSub']").on("ifClicked", function(event){
                var checkNum = $("input[name='coursewareCheckboxSub']:checked").length;
                if((checkNum+1)==checkBoxNum){
                    $("input[name='coursewareCheckboxAll']").iCheck("check");
                }
                var coursewareId = $(this).val();
                if(!$(this).prop("checked")){
                    var coursewareName = $(this).attr("coursewareName");
                    var checkedCoursewareArray = $("#checkedCoursewareIds").val().split(",");
                    if($.inArray(coursewareId, checkedCoursewareArray) < 0){
                        checkedCoursewareArray.push(coursewareId);
                        var coursewareName = $(this).attr("coursewareName");
                        var checkedCoursewareStr='<span class="btn btn-default btn-xs" id="checkedCourseware_'+coursewareId+'" style="margin: 0px 5px 5px 0px;">'+coursewareName+'<span aria-hidden="true" onclick=removeCheckedCourseware("'+coursewareId+'")>&nbsp;&times;</span></span>';
                        $("#checkedCoursewareIds").val(array_remove("", checkedCoursewareArray));
                        $("#checkedCoursewareArea").append(checkedCoursewareStr);
                    }
                }else{
                    $("input[name='coursewareCheckboxAll']").iCheck("uncheck");
                    removeCheckedCourseware(coursewareId);
                }
            });
        }else{
            $("#coursewarePageLimit").html("");
            lecturerListStr='<tr><td colspan="8" style="vertical-align:middle;"><h4 class="text-center"><small>没有找到相关数据</small></h4></td></tr>';
            $("#coursewareList").html(lecturerListStr);
            $("#coursewarePageLimitDiv").hide();
        }
    })
}

//数组移除某一项
function array_remove(value,array){
    var newArray = new Array();
    $.each(array,function(i,item){
        if(item != value){
            newArray.push(item);
        }
    })
    return newArray;
}

//数组去除重复值
function array_unique(array){
    array = array || [];
    var a = {};
    var len = array.length;
    for (var i=0; i<len;i++){
        var v = array[i];
        if (typeof(a[v]) == 'undefined'){
            a[v] = 1;
        }
    };
    array.length=0;
    for (var x in a){
        array[array.length] = x;
    }
    return array;
}

//移除已选的
function removeCheckedCourseware(id){
    $("#checkedCourseware_"+id).remove();
    var checkedCoursewareArray = $("#checkedCoursewareIds").val().split(",");
    $("#checkedCoursewareIds").val(array_remove(id, checkedCoursewareArray));
    $("input[name='coursewareCheckboxSub'][value='"+id+"']").iCheck("uncheck");
    $("input[name='coursewareCheckboxAll']").iCheck("uncheck");
}


//分页设置
function coursewarePageLimit(currentPage,totalPages,pageBarId) {
    var options = {
        currentPage: currentPage,
        totalPages: totalPages,
        numberOfPages: 5,
        bootstrapMajorVersion: 3,
        itemTexts: function (type, page, current) {
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上一页";
                case "next":
                    return "下一页";
                case "last":
                    return "尾页";
                case "page":
                    return page;
            }
        },
        tooltipTitles: function (type, page, current) {
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上一页";
                case "next":
                    return "下一页";
                case "last":
                    return "尾页";
                case "page":
                    return "第"+page+"页";
            }
        },
        onPageClicked: function (e, originalEvent, type, pageNo) {
            searchCoursewareList(pageNo);
        }
    }
    $("#"+pageBarId).bootstrapPaginator(options);
    $("#"+pageBarId).addClass("pagination-sm");
}